package com.smh.yunpicturebackend.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.*;
import com.smh.yunpicturebackend.config.property.OSSConfigProperties;
import com.smh.yunpicturebackend.exception.BusinessException;
import com.smh.yunpicturebackend.exception.ErrorCode;
import com.smh.yunpicturebackend.pojo.constant.FileConstant;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Formatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author shiminghui
 * @date 2025/6/17 11:12
 * @description: TODO
 */
@Slf4j
@Component
public class AliyunOSSUtils {

    private static final String FILE_PATH_PREFIX = "D:\\develop\\test-file";

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");

    @Resource
    private OSS ossClient;
    @Resource
    private OSSConfigProperties ossConfigProperties;

    /**
     * 根据文件名生成唯一ObjectName
     *
     * @param fileName 文件名
     * @return String 文件名
     */
    public String generateObjectName(String fileName) {
        if (fileName == null) {
            return null;
        }
        // 生成日期文件路径
        String format = dateFormat.format(new Date());
        // 生成唯一文件名
        String uuid = IdUtil.simpleUUID();
        // 截取文件后缀
        String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
        return format + "/" + uuid + fileSuffix;
    }

    /**
     * 上传文件到OSS
     *
     * @param bucketName 存储空间名称
     * @param objectName 文件路径+名称
     * @param file       文件
     * @return String 文件url
     */
    public String uploadFile(String bucketName, String objectName, File file) {
        try {
            ossClient.putObject(bucketName, objectName, file);
            return getFileUrl(bucketName, objectName);
        } catch (OSSException | ClientException e) {
            log.error("文件上传失败: " + e.getMessage());
            return null;
        }
    }

    public String uploadFile(String objectName, File file) {
        return uploadFile(ossConfigProperties.getBucketName(), objectName, file);
    }

    public String uploadFile(String objectName, MultipartFile multipartFile) {
        // 创建临时文件
        File tempFile = null;
        try {
            tempFile = File.createTempFile(FileConstant.TEMP_FILE_PREFIX + IdUtil.simpleUUID(), null);
            // 将MultipartFile转换为File
            multipartFile.transferTo(tempFile);
            return uploadFile(objectName, tempFile);
        } catch (IOException e) {
            log.error("创建临时文件失败:{}", e.getMessage(), e);
            return null;
        } finally {
            deleteTempFile(tempFile);
        }
    }

    /**
     * 下载文件
     *
     * @param bucketName 存储空间名称
     * @param objectName 文件路径+名称
     * @return String  文件路径
     */
    public String downloadFile(String bucketName, String objectName, String fileName) {
        try {
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            InputStream contentStream = ossObject.getObjectContent();
            File file = new File(FILE_PATH_PREFIX + "/" + fileName);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file);
            byte[] buffer = new byte[1024 * 1024];
            int bytesRead;
            while ((bytesRead = contentStream.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            fos.close();
            contentStream.close();
            return file.getAbsolutePath();
        } catch (OSSException | ClientException | IOException e) {
            log.error("文件下载失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 删除文件
     *
     * @param bucketName 存储空间名称
     * @param objectName 文件路径+名称
     * @return boolean 是否成功
     */
    public boolean deleteFile(String bucketName, String objectName) {
        try {
            ossClient.deleteObject(bucketName, objectName);
            return true;
        } catch (OSSException | ClientException e) {
            log.error("文件删除失败: {}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 批量删除文件
     *
     * @param bucketName     存储空间名称
     * @param objectNameList 文件列表
     * @return 删除的文件数量
     */
    public Integer deleteFiles(String bucketName, List<String> objectNameList) {
        DeleteObjectsRequest request = new DeleteObjectsRequest(bucketName);
        request.setKeys(objectNameList);
        DeleteObjectsResult result = ossClient.deleteObjects(request);
        return result.getDeletedObjects().size();
    }

    /**
     * 批量删除文件
     *
     * @param fileUrls 文件url列表
     * @return 删除的文件数量
     */
    public Integer deleteFiles(List<String> fileUrls) {
        // 解析文件路径
        List<String> objectNameList = fileUrls.stream().map(this::parseObjectName).collect(Collectors.toList());
        // 获取bucketName
        String bucketName = ossConfigProperties.getBucketName();
        return deleteFiles(bucketName, objectNameList);
    }


    /**
     * 删除临时文件
     *
     * @param tempFile 临时文件
     */
    private void deleteTempFile(File tempFile) {
        if (tempFile != null && tempFile.exists()) {
            boolean delete = tempFile.delete();
            if (!delete) {
                log.warn("删除临时文件失败:{}", tempFile.getAbsolutePath());
            }
        }
    }

    /**
     * 格式化文件类型并保存
     *
     * @param fileUrl 文件路径
     * @return 格式化后的文件路径
     */
    public String formatFileTypeAndSave(String fileUrl) {
        String bucketName = ossConfigProperties.getBucketName();

        // 将图片格式转化为webp,并保存到目标桶中
        StringBuilder sbStyle = new StringBuilder();
        Formatter styleFormatter = new Formatter(sbStyle);
        String styleType = "image/format,webp";
        // 将处理后的图片命名为example-resize.png并保存到当前Bucket。
        // 拿到图片的源文件名,将后缀改成webp
        // https://web-shiminghui.oss-cn-beijing.aliyuncs.com/public/2025/06/20/9b922c2e8ae44b5f9802d88bd0807351.png
        String sourceObjectName = parseObjectName(fileUrl);
        int lastIndexOf = sourceObjectName.lastIndexOf('.');

        String targetObjectName = sourceObjectName.substring(0, lastIndexOf) + ".webp";
        styleFormatter.format("%s|sys/saveas,o_%s,b_%s", styleType,
                BinaryUtil.toBase64String(targetObjectName.getBytes()),
                BinaryUtil.toBase64String(bucketName.getBytes()));
        // 创建ProcessObjectRequest
        ProcessObjectRequest request = new ProcessObjectRequest(bucketName, sourceObjectName, sbStyle.toString());
        ossClient.processObject(request);

        return getFileUrl(bucketName, targetObjectName);
    }

    /**
     * 缩略图
     *
     * @param fileUrl 文件Url
     * @param width   缩略图宽度
     * @param height  缩略图高度
     * @return 处理后的文件Url
     */
    public String thumbnailFileAndSave(String fileUrl, int width, int height) {
        String bucketName = ossConfigProperties.getBucketName();

        // 将图片缩略后保存到目标桶中
        StringBuilder sbStyle = new StringBuilder();
        Formatter styleFormatter = new Formatter(sbStyle);
        String styleType = "image/resize,m_fill,w_%s,h_%s";
        styleType = String.format(styleType, width, height);

        // 将处理后的图片命名为example-resize.png并保存到当前Bucket。
        // 拿到图片的源文件名,将后缀改成webp
        // https://web-shiminghui.oss-cn-beijing.aliyuncs.com/public/2025/06/20/9b922c2e8ae44b5f9802d88bd0807351.png
        String sourceObjectName = parseObjectName(fileUrl);

        int lastIndexOf = sourceObjectName.lastIndexOf('.');

        String targetObjectName = sourceObjectName.substring(0, lastIndexOf) + FileConstant.THUMBNAIL_SUFFIX + sourceObjectName.substring(lastIndexOf);
        styleFormatter.format("%s|sys/saveas,o_%s,b_%s", styleType,
                BinaryUtil.toBase64String(targetObjectName.getBytes()),
                BinaryUtil.toBase64String(bucketName.getBytes()));
        // 创建ProcessObjectRequest
        ProcessObjectRequest request = new ProcessObjectRequest(bucketName, sourceObjectName, sbStyle.toString());
        ossClient.processObject(request);

        return getFileUrl(bucketName, targetObjectName);
    }

    /**
     * 获取图片基本信息
     *
     * @param fileUrl 图片url
     * @return BaseImageInfo 图片基本信息
     */
    public BaseImageInfo getBaseImageInfo(String fileUrl) {
        String processStr = "x-oss-process=image/info";
        String content = HttpUtil.get(fileUrl + "?" + processStr);
        return BaseImageInfo.of(content);
    }

    /**
     * 获取图片平均颜色(即主色调)
     *
     * @param fileUrl 图片url
     * @return RGB
     */
    public String getImageAverageColor(String fileUrl) {
        String processStr = "x-oss-process=image/average-hue";
        String result = HttpUtil.get(fileUrl + "?" + processStr);
        JSONObject parseObj = JSONUtil.parseObj(result);
        if (parseObj.containsKey("RGB")) {
            return parseObj.getStr("RGB");
        }
        return null;
    }

    /**
     * 解析objectName
     *
     * @param fileUrl 文件url
     * @return objectName
     */
    public String parseObjectName(String fileUrl) {
        int i = fileUrl.indexOf(ossConfigProperties.getEndpoint());
        if (i == -1) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件路径异常");
        }
        return fileUrl.substring(i + ossConfigProperties.getEndpoint().length() + 1);
    }


    /**
     * 拼接可访问url
     *
     * @param bucketName 存储空间名称
     * @param objectName 文件路径+名称
     * @return String 文件url
     */
    public String getFileUrl(String bucketName, String objectName) {
        return "https://" + bucketName + "." + ossConfigProperties.getEndpoint() + "/" + objectName;
    }


    public static void main(String[] args) throws com.aliyuncs.exceptions.ClientException {
        // Endpoint以华东1（杭州）为例，填写为https://oss-cn-hangzhou.aliyuncs.com，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        String bucketName = generateUniqueBucketName("demo");
        // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-hangzhou。
        // 关于OSS支持的Region与Endpoint的对应关系，请参见https://www.alibabacloud.com/help/zh/oss/user-guide/regions-and-endpoints。
        String region = "cn-beijing";

        // 从环境变量中获取访问凭证。运行本代码示例之前，请先配置环境变量
        EnvironmentVariableCredentialsProvider credentialsProvider =
                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        // 创建OSSClient实例。
        // 当OSSClient实例不再使用时，调用shutdown方法以释放资源。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // 显式声明使用 V4 签名算法
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .region(region)
                .build();
        try {
            // 1. 创建存储空间（Bucket）
            ossClient.createBucket(bucketName);
            System.out.println("1. Bucket " + bucketName + " 创建成功。");
            // 2. 上传文件
            String objectName = "exampledir/exampleobject.txt";
            String content = "Hello OSS";
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));
            System.out.println("2. 文件 " + objectName + " 上传成功。");
            // 3. 下载文件
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            InputStream contentStream = ossObject.getObjectContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(contentStream));
            String line;
            System.out.println("3. 下载的文件内容：");
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            contentStream.close();
            // 4. 列出文件
            System.out.println("4. 列出 Bucket 中的文件：");
            ObjectListing objectListing = ossClient.listObjects(bucketName);
            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                System.out.println(" - " + objectSummary.getKey() + " (大小 = " + objectSummary.getSize() + ")");
            }
            // 5. 删除文件
            ossClient.deleteObject(bucketName, objectName);
            System.out.println("5. 文件 " + objectName + " 删除成功。");
            // 6. 删除存储空间（Bucket）
            ossClient.deleteBucket(bucketName);
            System.out.println("6. Bucket " + bucketName + " 删除成功。");
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException | IOException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    private void demo() throws com.aliyuncs.exceptions.ClientException, IOException {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "examplebucket";
        // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
        String sourceImage = "exampleimage.png";
        // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-hangzhou。
        String region = "cn-hangzhou";

        // 创建OSSClient实例。
        // 当OSSClient实例不再使用时，调用shutdown方法以释放资源。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // 将图片缩放为固定宽高100 px。
            StringBuilder sbStyle = new StringBuilder();
            Formatter styleFormatter = new Formatter(sbStyle);
            String styleType = "image/resize,m_fixed,w_100,h_100";
            // 将处理后的图片命名为example-resize.png并保存到当前Bucket。
            // 填写Object完整路径。Object完整路径中不能包含Bucket名称。
            String targetImage = "example-resize.png";
            styleFormatter.format("%s|sys/saveas,o_%s,b_%s", styleType,
                    BinaryUtil.toBase64String(targetImage.getBytes()),
                    BinaryUtil.toBase64String(bucketName.getBytes()));
            System.out.println(sbStyle.toString());
            ProcessObjectRequest request = new ProcessObjectRequest(bucketName, sourceImage, sbStyle.toString());
            GenericResult processResult = ossClient.processObject(request);
            String json = IOUtils.readStreamAsString(processResult.getResponse().getContent(), "UTF-8");
            processResult.getResponse().getContent().close();
            System.out.println(json);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    private static String generateUniqueBucketName(String demo) {
        return UUID.fastUUID().toString();
    }

    @Data
    @AllArgsConstructor
    public static class BaseImageInfo {
        //        {
//            "FileSize": {"value": "21839"},
//            "Format": {"value": "jpg"},
//            "FrameCount": {"value": "1"},
//            "ImageHeight": {"value": "267"},
//            "ImageWidth": {"value": "400"},
//            "ResolutionUnit": {"value": "1"},
//            "XResolution": {"value": "1/1"},
//            "YResolution": {"value": "1/1"}
//        }
        private Long fileSize;
        private String format;
        private Integer frameCount;
        private Integer imageHeight;
        private Integer imageWidth;
        private Integer resolutionUnit;
        private String xResolution;
        private String yResolution;

        public static BaseImageInfo of(String ImageInfoJsonStr) {
            if (ImageInfoJsonStr == null || ImageInfoJsonStr.isEmpty()) {
                return null;
            }
            JSONObject parsedObj = JSONUtil.parseObj(ImageInfoJsonStr);
            try {
                Long fileSize = null;
                String format = null;
                Integer frameCount = null;
                Integer imageHeight = null;
                Integer imageWidth = null;
                Integer resolutionUnit = null;
                String xResolution = null;
                String yResolution = null;

                if (parsedObj.containsKey("FileSize")) {
                    JSONObject fileSizeObj = parsedObj.getJSONObject("FileSize");
                    if (fileSizeObj != null && fileSizeObj.containsKey("value")) {
                        String value = fileSizeObj.getStr("value");
                        if (value != null) {
                            fileSize = Long.parseLong(value);
                        }
                    }
                }

                if (parsedObj.containsKey("Format")) {
                    JSONObject formatObj = parsedObj.getJSONObject("Format");
                    if (formatObj != null && formatObj.containsKey("value")) {
                        format = formatObj.getStr("value");
                    }
                }

                if (parsedObj.containsKey("FrameCount")) {
                    JSONObject frameCountObj = parsedObj.getJSONObject("FrameCount");
                    if (frameCountObj != null && frameCountObj.containsKey("value")) {
                        String value = frameCountObj.getStr("value");
                        if (value != null) {
                            frameCount = Integer.parseInt(value);
                        }
                    }
                }

                if (parsedObj.containsKey("ImageHeight")) {
                    JSONObject imageHeightObj = parsedObj.getJSONObject("ImageHeight");
                    if (imageHeightObj != null && imageHeightObj.containsKey("value")) {
                        String value = imageHeightObj.getStr("value");
                        if (value != null) {
                            imageHeight = Integer.parseInt(value);
                        }
                    }
                }

                if (parsedObj.containsKey("ImageWidth")) {
                    JSONObject imageWidthObj = parsedObj.getJSONObject("ImageWidth");
                    if (imageWidthObj != null && imageWidthObj.containsKey("value")) {
                        String value = imageWidthObj.getStr("value");
                        if (value != null) {
                            imageWidth = Integer.parseInt(value);
                        }
                    }
                }

                if (parsedObj.containsKey("ResolutionUnit")) {
                    JSONObject resolutionUnitObj = parsedObj.getJSONObject("ResolutionUnit");
                    if (resolutionUnitObj != null && resolutionUnitObj.containsKey("value")) {
                        String value = resolutionUnitObj.getStr("value");
                        if (value != null) {
                            resolutionUnit = Integer.parseInt(value);
                        }
                    }
                }

                if (parsedObj.containsKey("XResolution")) {
                    JSONObject xResolutionObj = parsedObj.getJSONObject("XResolution");
                    if (xResolutionObj != null && xResolutionObj.containsKey("value")) {
                        xResolution = xResolutionObj.getStr("value");
                    }
                }

                if (parsedObj.containsKey("YResolution")) {
                    JSONObject yResolutionObj = parsedObj.getJSONObject("YResolution");
                    if (yResolutionObj != null && yResolutionObj.containsKey("value")) {
                        yResolution = yResolutionObj.getStr("value");
                    }
                }

                return new BaseImageInfo(fileSize, format, frameCount, imageHeight, imageWidth, resolutionUnit, xResolution, yResolution);

            } catch (Exception e) {
                log.info("图片信息解析失败: {}", e.getMessage(), e);
                return null;
            }
        }
    }

}
